package com.pansoft.androidcomp;

import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

/**
 * 一个具有自动重用View功能的适配器实现
 * 
 * @author zhangjg
 * @date Feb 20, 2014 10:57:42 AM
 */
public abstract  class AutoReuseViewAdapter extends BaseAdapter {

	//Item布局资源
	private int itemLayoutRes;
	
	//Item中要操作的各个子View的Id
	private int[] childViewIds;

	//布局填充器
	private LayoutInflater inflator;

	
	public AutoReuseViewAdapter(Context context, int itemLayoutRes, int ... childViewIds) {
		
		inflator = LayoutInflater.from(context);

		this.itemLayoutRes = itemLayoutRes;
		this.childViewIds = childViewIds;

	}


	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		View v = null;
		
		ViewHolder holder;
		
		
		if(convertView != null){   
			v = convertView;      
			holder = (ViewHolder) v.getTag();
		}else{
			v = inflator.inflate(itemLayoutRes, null);
			
			holder = new ViewHolder();
			
			for(int childId : childViewIds ){
				holder.cacheView(v.findViewById(childId));
			}
			
			v.setTag(holder);
		}
		
		boundDataAndEventToViews(position, v, holder.getCachedViews());
		
		return v;
	}

	/**
	 * 抽象方法， 被子类覆盖， 将业务相关的数据和事件绑定到特定的子View上
	 */
	protected abstract void boundDataAndEventToViews(int position,
			View itemView, ArrayList<View> childViews);

	
	/**
	 * 内部类， 用于缓存条目View的子控件， 同样是面向抽象和业务无关的
	 * 
	 * @author zhangjg
	 * @date Feb 20, 2014 9:12:33 AM
	 */
	private static class ViewHolder{
		private ArrayList<View> cachedViews = new ArrayList<View>();
		
		public void cacheView(View v){
			cachedViews.add(v);
		}
		
		public ArrayList<View> getCachedViews(){
			return cachedViews;
		}
	}

}